<template>
  <uni-popup ref="filterPop" :safeArea="false" @change="popChange" @maskClick="closePop">
    <view class="input-pop">
      <view class="header">
        <text>更多查询</text>
        <uni-icons class="close-icon" @click="closePop" type="closeempty" size="20px" color="#CCCCCC" />
      </view>
      <view class="conent-wrap">
        <view class="main">
          <view class="items">
            <view class="label">时间维度</view>
            <view class="select-wrap" :style="{
                color: timeTypeText ? '#333' : '#D9D9D9'
              }" @click="openSinglePanel('timeTypeList')">
              <text>{{ timeTypeText ? timeTypeText : '请选择时间维度' }}</text>
              <uni-icons class="select-icon" type="right" size="20" color="#D9D9D9"></uni-icons>
            </view>
          </view>
          <view v-if="orgShow" class="items">
            <view class="label">组织名称</view>
            <view class="select-wrap" :style="{
              color: orgnameText ? '#333' : '#D9D9D9'
            }" @click="openMultiplePanel('orgNamesLists')">
              <text>{{ orgnameText ? orgnameText : '请选择组织名称' }}</text>
              <uni-icons class="select-icon" type="right" size="20" color="#D9D9D9"></uni-icons>
            </view>
          </view>
          <view v-if="isShowCustomer" class="items">
            <view class="label">客户</view>
            <view class="select-wrap" :style="{
              color: customerText ? '#333' : '#D9D9D9'
            }" @click="openMultiplePanel('customerList')">
              <text>{{ customerText ? customerText : '请选择客户' }}</text>
              <uni-icons class="select-icon" type="right" size="20" color="#D9D9D9"></uni-icons>
            </view>
          </view>
          <view v-if="isShowSupplier" class="items">
            <view class="label">供应商</view>
            <view class="select-wrap" :style="{
              color: supplierText ? '#333' : '#D9D9D9'
            }" @click="openMultiplePanel('supplierList')">
              <text>{{ supplierText ? supplierText : '请选择供应商' }}</text>
              <uni-icons class="select-icon" type="right" size="20" color="#D9D9D9"></uni-icons>
            </view>
          </view>
          <view v-if="isShowCoalType" class="items">
            <view class="label">产品</view>
            <view class="select-wrap" :style="{
              color: coalTypeText ? '#333' : '#D9D9D9'
            }" @click="openMultiplePanel('coalTypeList')">
              <text>{{ coalTypeText ? coalTypeText : '请选择产品' }}</text>
              <uni-icons class="select-icon" type="right" size="20" color="#D9D9D9"></uni-icons>
            </view>
          </view>
          <view v-if="isShowProduct" class="items">
            <view class="label">产品</view>
            <view class="select-wrap" :style="{
              color: productText ? '#333' : '#D9D9D9'
            }" @click="openMultiplePanel('productList')">
              <text>{{ productText ? productText : '请选择产品' }}</text>
              <uni-icons class="select-icon" type="right" size="20" color="#D9D9D9"></uni-icons>
            </view>
          </view>
        </view>
        <view class="footer">
          <button class="cancel" @click="resetFilter()">重置</button>
          <button type="primary" @click="confirmFilter()">查询</button>
        </view>
        <scroll-view class="scroll-view" scroll-y="true" v-if="singleFlag">
          <view v-if="singleSearch" class="search-box">
            <uni-easyinput ref="easyinputRef" suffixIcon="search" v-model="searchKeyword" placeholder="请输入关键字"
              @input="filterKeywordList('single')" :maxlength="50"></uni-easyinput>
          </view>
          <view class="scroll-main" :style="{height: singleSearch?'340rpx':'450rpx'}">
            <view :key="index" class="scroll-view-item" @click="singleChoiceChange(item)"
              :class="{ 'active-item': item.checked }" v-for="(item, index) in singleList">
              <view>{{ item.label }}</view>
              <view class="checked-icon" v-if="item.checked">√</view>
            </view>
          </view>
          <view class="scroll-single-footer">
            <button class="cancel" plain size="mini" @click="cancleSinglePanel">
              取消
            </button>
          </view>
        </scroll-view>
        <scroll-view class="scroll-view" scroll-y="true" v-if="multipleFlag">
          <view v-if="multipleSearch" class="search-box">
            <uni-easyinput ref="easyinputRef" suffixIcon="search" v-model="searchKeyword" placeholder="请输入关键字"
              @input="filterKeywordList('multiple')" :maxlength="50"></uni-easyinput>
          </view>
          <view class="scroll-main" :style="{height: multipleSearch?'340rpx':'534rpx'}">
            <view :key="index" class="scroll-view-item" @click="multipleChoiceChange(item)"
              :class="{ 'active-item': item.checked }" v-for="(item, index) in multipleList">
              <view>{{ item.label }}</view>
              <view class="checked-icon" v-if="item.checked">√</view>
            </view>
          </view>
          <view class="scroll-multiple-footer">
            <button class="cancel" plain size="mini" @click="cancleMultiplePanel">
              取消
            </button>
            <button plain size="mini" type="primary" @click="confirmMultiplePanel">
              确定
            </button>
          </view>
        </scroll-view>
      </view>
    </view>
  </uni-popup>
</template>
<script>
  import { toast } from '@/utils/common';
  import { findProCusRelNameByCusIds } from '@/api/reportTable'
  export default {
    props: {
      show: {
        type: Boolean,
        default: false
      },
      orgShow: {
        type: Boolean,
        default: false
      },
      isShowCustomer: {
        type: Boolean,
        default: true
      },
      isShowSupplier: {
        type: Boolean,
        default: true
      },
      isShowCoalType: {
        type: Boolean,
        default: true
      },
      isShowProduct: {
        type: Boolean,
        default: true
      },
      isLinkage: {
        type: Boolean,
        default: false
      },
      singleSearch: {
        type: Boolean,
        default: false
      },
      multipleSearch: {
        type: Boolean,
        default: false
      },
      supplierList: {
        type: Array,
        default: []
      },
      customerList: {
        type: Array,
        default: []
      },
      orgNamesLists: {
        type: Array,
        default: []
      },
      coalTypeList: {
        type: Array,
        default: []
      }
    },
    watch: {
      show(value) {
        if (value) {

          this.singleFlag = false
          this.multipleFlag = false
          this.searchKeyword = undefined
          this.$refs.easyinputRef?.onClear()
          this.$refs.filterPop?.open('bottom');
          return;
        }
        this.$refs.filterPop?.close();
      },
      isShowCustomer: {
        immediate: true,
        handler(value) {
          if (!value) {
            this.timeTypeList = [
              {
                value: 5,
                label: '矿发时间',
                checked: false
              },
              {
                value: 10,
                label: '轻磅时间',
                checked: true
              },
              {
                value: 20,
                label: '重磅时间',
                checked: false
              },
              {
                value: 30,
                label: '出场时间',
                checked: false
              }
            ]
            this.filterInput.timeType = 10
          }
        }
      },
      isShowSupplier: {
        immediate: true,
        handler(value) {
          if (!value) {
            this.timeTypeList = [
              {
                value: 10,
                label: '轻磅时间',
                checked: true
              },
              {
                value: 20,
                label: '重磅时间',
                checked: false
              }
            ]
            this.filterInput.timeType = 20
          }
        }
      }
    },
    computed: {
      timeTypeText() {
        const filter = this.timeTypeList.find(e => this.filterInput.timeType === e.value)
        return filter?.label || ''
      },
      customerText() {
        const filter = this.customerList.filter(e => this.filterInput.customer.includes(e.value))
        return filter.map(e => e.label).join(',')
      },
      orgnameText() {
        const filter = this.orgNamesLists.filter(e => this.filterInput.organizationIds.includes(e.value))
        return filter.map(e => e.label).join(',')
      },
      supplierText() {
        const filter = this.supplierList.filter(e => this.filterInput.supplier.includes(e.value))
        return filter.map(e => e.label).join(',')
      },
      coalTypeText() {
        const filter = this.coalTypeList.filter(e => this.filterInput.coalType.includes(e.value))
        return filter.map(e => e.label).join(',')
      },
      productText() {
        const filter = this.productList.filter(e => this.filterInput.product.includes(e.value))
        return filter.map(e => e.label).join(',')
      },
    },

    data() {
      return {
        singleFlag: false,
        multipleFlag: false,
        searchKeyword: undefined,
        singleType: undefined,
        multipleType: undefined,
        keyMap: {
          timeTypeList: 'timeType',
          customerList: 'customer',
          orgNamesLists: 'organizationIds',
          supplierList: 'supplier',
          coalTypeList: 'coalType',
          productList: 'product'
        },
        filterInput: {
          timeType: undefined,
          supplier: [],
          organizationIds: [],
          customer: [],
          coalType: [],
          product: []
        },
        singleList: [],
        multipleList: [],
        productList: [],
        timeTypeList: [
          {
            value: 5,
            label: '矿发时间',
            checked: false
          },
          {
            value: 10,
            label: '轻磅时间',
            checked: true
          },
          {
            value: 20,
            label: '重磅时间',
            checked: false
          },
          {
            value: 30,
            label: '出场时间',
            checked: false
          }
        ]
      };
    },
    methods: {
      popChange(data) {
        this.$emit('openChange', {
          key: 'isOpenFilterBox',
          show: data.show
        });
      },
      closePop() {
        this.$refs.filterPop?.close();
        this.$emit('closePop');
      },
      resetFilter() {
        this.singleList = []
        this.multipleList = []
        this.productList = []
        this.filterInput = {
          timeType: undefined,
          customer: [],
          organizationIds: [],
          supplier: [],
          coalType: [],
          product: []
        };
        if (!this.isShowCustomer) {
          this.filterInput.timeType = 10
        }
        if (!this.isShowSupplier) {
          this.filterInput.timeType = 20
        }
      },
      filterKeywordList(type) {
        if (type === 'single') {
          const list = JSON.parse(JSON.stringify(this[this.singleType]))
          this.singleList = list.filter(e => e.label.includes(this.searchKeyword))
        }
        if (type === 'multiple') {
          const list = JSON.parse(JSON.stringify(this[this.multipleType]))
          this.multipleList = list.filter(e => e.label.includes(this.searchKeyword))
        }
      },
      openSinglePanel(key) {
        this.singleType = key
        this.deepCloneList('singleList', this[key])
        this.recoverStatus(this.keyMap[key], 'singleList', false)
        this.singleFlag = true
      },
      cancleSinglePanel() {
        this.searchKeyword = undefined
        this.singleFlag = false
      },
      openMultiplePanel(key) {

        if (key === 'productList') {
          if (this.filterInput.customer.length === 0) {
            toast('请先选择客户列表')
            return
          }
          if (this[key].length === 0) {
            toast('产品列表暂无数据')
            return
          }
        }
        this.multipleType = key;
        this.deepCloneList('multipleList', this[key])
        this.recoverStatus(this.keyMap[key], 'multipleList', true)
        this.multipleFlag = true
      },
      cancleMultiplePanel() {
        this.resetMultipleList(this.filterInput[this.keyMap[this.multipleType]])
        this.searchKeyword = undefined
        this.$refs.easyinputRef?.onClear()
        this.multipleFlag = false
      },
      deepCloneList(key, list) {
        this[key] = JSON.parse(JSON.stringify(list))
      },
      confirmMultiplePanel() {
        this.filterInput[this.keyMap[this.multipleType]] = this.handleConfirm()
        if (this.multipleType === 'customerList' && this.isLinkage) {
          this.productList = []
          this.filterInput.product = []
          if (this.handleConfirm().length > 0) {
            this.findProCusRelNameByCusIds(this.handleConfirm())
          }
        }
        this.searchKeyword = undefined
        this.$refs.easyinputRef?.onClear()
        this.multipleFlag = false
      },
      async findProCusRelNameByCusIds(ids) {
        const res = await findProCusRelNameByCusIds({ cusIds: ids.join(',') })
        if (res.code === 0) {
          const result = res.data || []
          this.productList = result.map(e => {
            return {
              value: e.proId,
              checked: false,
              label: e.proName
            }
          })
        } else {
          toast(res.msg)
        }
      },
      singleChoiceChange(item) {
        this.filterInput.timeType = item.value
        this.searchKeyword = undefined
        this.$refs.easyinputRef?.onClear()
        this.singleFlag = false
      },
      multipleChoiceChange(item) {
        this.multipleList.forEach(e => {
          if (item.value === e.value) {
            e.checked = !e.checked
          }
        })
      },
      handleConfirm() {
        return this.multipleList.filter(e => e.checked).map(m => m.value)
      },
      resetMultipleList(currentMultiple) {
        this.multipleList.map(e => {
          if (currentMultiple.includes(e.value)) {
            e.checked = true
          } else {
            e.checked = false
          }
        })
      },
      confirmFilter() {
        this.$emit('filterChange', this.filterInput);
        this.$refs.filterPop?.close();
      },
      recoverStatus(key, listKey, isMultiple) {
        const value = this.filterInput[key]
        this[listKey].forEach(e => {
          if (isMultiple ? value.includes(e.value) : value === e.value) {
            e.checked = true
          } else {
            e.checked = false
          }
        })
      }
    }
  };
</script>
<style lang="scss" scoped>
  .input-pop {
    border-radius: 20rpx 20rpx 0 0 !important;
    background-color: #ffffff;

    .conent-wrap {
      display: flex;
      flex-direction: column;
      position: relative;
      max-height: 55vh;
    }

    .header {
      position: relative;
      padding: 20rpx 36rpx;
      text-align: center;
      border-bottom: 2rpx solid #eaeaea;

      .close-icon {
        position: absolute;
        right: 36rpx;
      }

      text {
        font-size: 26rpx;
        font-weight: bold;
      }
    }

    .main {
      padding: 36rpx 36rpx 0 36rpx;
      flex: 1;
      height: 0;
      overflow-y: auto;
    }

    .footer {
      padding: 40rpx;
      display: flex;
      justify-content: space-between;
    }

    button {
      width: 45%;
      margin-top: 18rpx;
      height: 70rpx !important;
      font-size: 28rpx !important;
      line-height: 70rpx !important;
    }

    button[type="primary"] {
      color: #ffffff;
      background-color: #409eff;
    }

    button.cancel {
      border: 0 !important;
      color: #666666 !important;
      background-color: #eeeff2 !important;
    }
  }

  .scroll-view {
    position: absolute;
    padding: 18rpx 36rpx 0 36rpx;
    width: 100%;
    height: 100%;
    z-index: 9;
    top: 0;
    background-color: #fff;

    .scroll-view-item+.scroll-view-item {
      margin-top: 10rpx;
    }

    .search-box {
      margin: 0 0 20rpx 4rpx;
    }

    .scroll-view-item {
      display: flex;
      justify-content: space-between;
      padding: 16rpx 18rpx;
      border-radius: 8rpx;
      background-color: #f2f6fc;

      .checked-icon {
        position: relative;
        font-size: 24rpx;
        font-weight: bold;
        top: 8rpx;
      }
    }

    .scroll-main {
      overflow-y: auto;
    }

    .scroll-single-footer,
    .scroll-multiple-footer {
      padding: 40rpx 24rpx 20rpx 24rpx;
      display: flex;

      button {
        margin: 0 !important;
        width: 300rpx;
      }
    }

    .scroll-single-footer {
      justify-content: flex-end;
    }

    .scroll-multiple-footer {
      justify-content: space-between;
    }
  }

  .active-item {
    color: #fff !important;
    background-color: #409eff !important;
  }

  .items {
    margin-bottom: 20rpx;
    display: block;

    .middle-icon {
      padding: 0 8rpx;
    }

    .label {
      width: 80px;
      margin-bottom: 8rpx;
      display: flex;
      align-items: center;

      >text {
        color: red;
      }
    }

    .items-input {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: start;
    }

    input {
      flex: 1;
      height: 70rpx;
      color: #999;
      line-height: 70rpx;
      border-radius: 8rpx;
      padding: 0px 18rpx;
      border: 2rpx solid #e5e5e5;
    }

    .select-wrap {
      position: relative;
      flex: 1;
      height: 70rpx;
      padding: 0 18rpx;
      color: #808080;
      line-height: 70rpx;
      border-radius: 8rpx;
      border: 2rpx solid #e5e5e5;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      .select-icon {
        position: absolute;
        right: 10rpx;
      }
    }

    .address-box {
      display: flex;
      flex: 1;

      button {
        width: 36%;
        margin-left: 18rpx;
      }
    }
  }
</style>